//
//  TabBarController.swift
//  FMRadio
//
//  Created by 范东 on 2022/7/26.
//

import UIKit
import FDUIKit

class TabBarController: UITabBarController {
    
    var nowPlayingView: NowPlayingView?
    
    var callVC: VideoCallViewController?
    var joinVC: JoinViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        nowPlayingView = NowPlayingView(frame: .zero)
        nowPlayingView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(nowBtnAction)))
        view.addSubview(nowPlayingView!)
        nowPlayingView?.snp.makeConstraints({ make in
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
            make.bottom.equalToSuperview().offset(-CGFloat.tabBarHeight)
        })
        
        let homeVC = NestViewController()
        let homeNav = TUINavigationController(rootViewController: homeVC)
        homeNav.tabBarItem = UITabBarItem(title: "电台", image: UIImage(systemName: "radio"), tag: 0)
        let convVC = ConversationController()
        let convNav = TUINavigationController(rootViewController: convVC)
        convNav.tabBarItem = UITabBarItem(title: "消息", image: UIImage(systemName: "message"), tag: 0)
        let mineVC = MineViewController()
        let mineNav = TUINavigationController(rootViewController: mineVC)
        mineNav.tabBarItem = UITabBarItem(title: "我的", image: UIImage(systemName: "person"), tag: 0)
        
        viewControllers = [homeNav, convNav, mineNav]
        
        V2TIMManager.sharedInstance().addSimpleMsgListener(listener: self)
        V2TIMManager.sharedInstance().addConversationListener(listener: self)
        
        delegate = self
        
        UIApplication.shared.beginReceivingRemoteControlEvents()
        self.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIApplication.shared.endReceivingRemoteControlEvents()
        resignFirstResponder()
    }
    
    @objc func nowBtnAction(){
        if nowPlayingView?.model == nil {
            return
        }
        let nowPlayVC = NowPlayingViewController()
        nowPlayVC.model = nowPlayingView?.model ?? RadioResponseModelRadio()
        let nav = TUINavigationController(rootViewController: nowPlayVC)
        present(nav, animated: true, completion: nil)
    }
    
}

extension TabBarController: V2TIMSimpleMsgListener{
    func onRecvC2CCustomMessage(_ msgID: String!, sender info: V2TIMUserInfo!, customData data: Data!) {
        do {
            V2TIMManager.sharedInstance().markC2CMessage(asRead: info.userID) {
                debugPrint("设置已读成功")
            } fail: { code, msg in
                debugPrint("设置已读失败 code:\(code) msg:"+(msg ?? ""))
            }
            
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
            let model = MessageModel.deserialize(from: json) ?? MessageModel()
            switch model.type {
            case MessageType.callStart.rawValue:
                V2TIMManager.sharedInstance().getGroupMembersInfo(.FullGroupId, memberList: [info.userID]) { infos in
                    let joinVC = JoinViewController()
                    joinVC.fromUser = (infos?.first!)!
                    joinVC.channelId = model.channelId
                    joinVC.type = CallType(rawValue: model.callType)!
                    joinVC.modalPresentationStyle = .fullScreen
                    FMRadio.shared.tabC?.joinVC = joinVC
                    self.present(joinVC, animated: true, completion: nil)
                } fail: { code, msg in
                    debugPrint("获取用户信息失败 code:\(code) msg:"+(msg ?? ""))
                }
                break
            case MessageType.callAccept.rawValue:
                
                break
            case MessageType.callRefuse.rawValue:
                FMRadio.shared.tabC?.callVC?.dismiss(animated: true, completion: {
                    self.view.makeToast(NSLocalizedString("The other party has refused", comment: ""))
                })
                break
            case MessageType.callEnd.rawValue:
                FMRadio.shared.tabC?.callVC?.dismiss(animated: true, completion: {
                    self.view.makeToast(NSLocalizedString("The other party has hung up", comment: ""))
                })
                FMRadio.shared.tabC?.joinVC?.dismiss(animated: true, completion: {
                    self.view.makeToast(NSLocalizedString("The other party has hung up", comment: ""))
                })
                break
            default:
                break
            }
        } catch let error {
            debugPrint(error.localizedDescription)
        }
    }
}

extension TabBarController: V2TIMConversationListener{
    func onTotalUnreadMessageCountChanged(_ totalUnreadCount: UInt64) {
        if totalUnreadCount > 0 {
            tabBar.items?[1].badgeValue = "\(totalUnreadCount)"
        }else{
            tabBar.items?[1].badgeValue = nil
        }
        UIApplication.shared.applicationIconBadgeNumber = Int(totalUnreadCount)
    }
}

extension TabBarController: UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let index = viewControllers?.firstIndex(of: viewController)
        if index != 0 {
            if V2TIMManager.sharedInstance().getLoginStatus() != .STATUS_LOGINED {
                let loginVC = LoginViewController()
                present(loginVC, animated: true, completion: nil)
                return false
            }
            return true
        }
        return true
    }
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        UIImpactFeedbackGenerator(style: .medium).impactOccurred()
    }
    
}

extension TabBarController{
    override func remoteControlReceived(with event: UIEvent?) {
        
        let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as! SceneDelegate
        let tabBarC = sceneDelegate.window?.rootViewController as! TabBarController
        
        switch event?.subtype {
        case .remoteControlPlay:
            FDAudioPlayerManager.defaultManager.resume()
            tabBarC.nowPlayingView?.playState = .playing
            break
        case .remoteControlStop:
            FDAudioPlayerManager.defaultManager.stop()
            tabBarC.nowPlayingView?.playState = .stopped
            break
        case .remoteControlPause:
            FDAudioPlayerManager.defaultManager.stop()
            tabBarC.nowPlayingView?.playState = .paused
            break
        case .remoteControlNextTrack:
            print("remoteControlNextTrack")
            break
        case .remoteControlPreviousTrack:
            print("remoteControlPreviousTrack")
            break
        case .remoteControlTogglePlayPause:
            print("remoteControlTogglePlayPause")
            break
        default:
            break
        }
    }
}
